package models

import (
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"time"
)

type AlarmReason = string

const (
	Alarm        AlarmReason = "alarm"
	Recovery     AlarmReason = "recovery"
	CollectDelay AlarmReason = "collect_delay"
)

// AlarmRecord 告警记录
type AlarmRecord struct {
	Id                    int64
	AlarmConfigId         int64 `xorm:"alert_config_id"`
	AlarmRecordCategoryId int64 `xorm:"alert_record_category_id"`

	Reason     AlarmReason `xorm:"reason varchar(20)"` // 告警原因
	Level      string      `xorm:"level varchar(50)"`  // 告警级别
	Pushed     bool        `xorm:"pushed varchar(50)"` // 是否已推送
	Message    string      `xorm:"message"`
	IsObsolete bool        `xorm:"is_obsolete"` // 是否作废
	Created    time.Time   `xorm:"created"`
}

func (AlarmRecord) TableName() string {
	return "alarm_flow.alarm_record"
}

// AlarmRecordCategory 将告警记录进行分类，分类逻辑见方法 GenerateUniqueId
type AlarmRecordCategory struct {
	Id            int64
	UniqueId      string `xorm:"unique_id varchar(32)"`
	AlarmConfigId int64  `xorm:"alert_config_id"`

	CollectItemName string `xorm:"collect_item_name"`
	AlarmConfigName string `xorm:"alarm_config_name"`
	CmdbInstId      int64  `xorm:"cmdb_inst_id"`
	SerialNumber    string `xorm:"serial_number varchar(50)"`
	Hostname        string `xorm:"hostname varchar(50)"`
}

func (r AlarmRecordCategory) GenerateUniqueId() string {
	input := fmt.Sprintf("%s.%s.%s", r.CollectItemName, r.AlarmConfigName, r.SerialNumber)

	hash := sha256.Sum256([]byte(input))
	// 将哈希值编码为 Base64 字符串
	base64Str := base64.StdEncoding.EncodeToString(hash[:])
	return base64Str
}

func (AlarmRecordCategory) TableName() string {
	return "alarm_flow.alarm_record_category"
}

// PushRecord 推送记录
type PushRecord struct {
	Id                    int64
	AlarmRecordId         int64 `xorm:"alert_record_id"`
	AlarmRecordCategoryId int64 `xorm:"alert_record_category_id"`

	NoticeConfigName string    `xorm:"notice_config_name"`
	StatusCode       int       `xorm:"status_code"`
	Resp             string    `xorm:"resp varchar(1024)"`
	Updated          time.Time `xorm:"updated"`
	Created          time.Time `xorm:"created"`
}

func (PushRecord) TableName() string {
	return "alarm_flow.push_record"
}
